package com.xxadmin.common.web;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Spring mvc 最基础的Controller，用于获取Request、Response、Session、Model对象
 *
 * @author:chenming
 * @date : 2018/03/30
 */
public class HttpBaseController {

    /**
     * ThreadLocal确保高并发下每个请求的request，response都是独立的
     */

    /** 当前线程的request 对象*/
    private static ThreadLocal<HttpServletRequest> currentThreadRequest = new ThreadLocal<>();

    /** 当前线程的response对象 **/
    private static ThreadLocal<HttpServletResponse> currentThreadResponse = new ThreadLocal<>();

    /** 当前线程的model对象 */
    private static ThreadLocal<Model> currentThreadModel = new ThreadLocal<>();

    /**
     * 初始化request、response对象<br>
     * ModelAttribute注解能够确保其标识的方法在每个控制器中的方法访问之前先调用
     *
     *
     * @param request
     * @param response
     */
    @ModelAttribute
    public void initReqAndRep(HttpServletRequest request , HttpServletResponse response,Model model){
        currentThreadRequest.set(request);
        currentThreadResponse.set(response);
        currentThreadModel.set(model);
    }

    /**
     * 获取当前线程的request对象
     *
     * @return
     */
    protected HttpServletRequest getRequest(){
        return currentThreadRequest.get();
    }

    /**
     * 获取当前线程的response对象
     *
     * @return
     */
    protected HttpServletResponse getResponse(){
        return currentThreadResponse.get();
    }

    /**
     * 获取当前线程的session对象
     */
    protected HttpSession getSession(){
        return getRequest().getSession();
    }

    /**
     * 获取当前线程的model对象
     *
     */
    protected Model getModel(){
        return currentThreadModel.get();
    }

    /**
     * 向当前线程的model设置值
     *
     * @param key  key
     * @param value value
     */
    protected void setModelAttribute(String key,Object value){
        getModel().addAttribute(key, value);
    }

    /**
     * 向session中设置值
     *
     * @param key
     * @param value
     */
    protected void setSessionAttribute(String key,Object value){
        getSession().setAttribute(key, value);
    }
}
